package com.chookss.home.gallery;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.UploadEntity;
import com.chookss.mine.personal.upload.MyUploadRecordActivity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class UploadGalleryService extends Service {

    public static int NotificationId = 5;
    private UploadEntity uploadEntity;
    private String uploadTag="";
    private boolean stopUpload=false;//默认正常上传  当true时切换账号中止上传
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initNotification();
        startTimer();
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        uploadEntity = (UploadEntity) intent.getSerializableExtra("data");
        if(uploadEntity==null){
            stopSelf();
        }else{
            uploadTag=uploadEntity.getUploadTag();
            uploadData();
        }
        return super.onStartCommand(intent, flags, startId);
    }


    private void uploadData() {
        if(uploadEntity==null){
            stopSelf();
        }
        List<File> files = new ArrayList<>();
        for (int i = 0; i < uploadEntity.getImage().getImgList().size(); i++) {
            files.add(new File(uploadEntity.getImage().getImgList().get(i)));
        }
        Map<String, String> map = new HashMap<>();
        map.put("imageKeyWord", uploadEntity.getImage().getImageKeyWord());
        map.put("imageUploadLocation",uploadEntity.getImage().getImageUploadLocation());
        map.put("imageUploadLocationProvince", uploadEntity.getImage().getImageUploadLocationProvince());
        map.put("imageUploadLocationCity",uploadEntity.getImage().getImageUploadLocationCity());
        map.put("imageUploadLocationCounty",uploadEntity.getImage().getImageUploadLocationCounty());
        map.put("imageUploadLocationJd", uploadEntity.getImage().getImageUploadLocationJd());
        map.put("imageUploadLocationWd",uploadEntity.getImage().getImageUploadLocationWd());
        map.put("provideEmployeeCode",uploadEntity.getImage().getProvideEmployeeCode());
        map.put("provideEmployeeName",uploadEntity.getImage().getProvideEmployeeName());
        map.put("tagCodes", uploadEntity.getImage().getTagCodes());
        map.put("catalogCodes", uploadEntity.getImage().getCatalogCodes());
        map.put("imageOpenStatus",uploadEntity.getImage().getImageOpenStatus());
        map.put("shareFlag",uploadEntity.getImage().getShareFlag());
        map.put("original", uploadEntity.getImage().getOriginal());
        if(stopUpload){
            stopSelf();
            return;
        }
        MyHttpRequest.upLoadFiles(Urls.insertImage, this, map, "fileList", files, new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    if(stopUpload){
                        stopSelf();
                        return;
                    }
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshGallery"));
                        EventBus.getDefault().post(new MyEvent("RefreshDirectory"));
                        MyToast.show("图片发布成功");
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 100;
                        handler.sendMessage(msg);
                        FileUtilss.delFile(uploadEntity.getImage().getImgList());
                        XJson.deleteUploadEntity(UploadGalleryService.this, uploadEntity, UploadEntity.class);
                        Intent intent = new Intent();
                        intent.setPackage(getPackageName());
                        intent.setAction(MyUploadRecordActivity.picTag);
                        intent.putExtra("tag", uploadTag);
                        intent.putExtra("percent", 100);
                        LocalBroadcastManager.getInstance(UploadGalleryService.this).sendBroadcast(intent);
                        EventBus.getDefault().post(new MyEvent("refreshUploadRecord"));
                        stopSelf();
                    } else {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 100;
                        handler.sendMessage(msg);
                        EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("图片发布失败，请稍后重试");
                    EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                    stopSelf();
                }
            }
        });
    }

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private int timePercent = 0;

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    timePercent = timePercent + new Random().nextInt(6);
                    if (timePercent > 99) {
                        timePercent = 99;
                    }
                    Message msg = handler.obtainMessage();
                    msg.arg1 = timePercent;
                    handler.sendMessage(msg);
                    Intent intent = new Intent();
                    intent.setPackage(getPackageName());
                    intent.setAction(MyUploadRecordActivity.picTag);
                    intent.putExtra("tag", uploadTag);
                    intent.putExtra("percent", timePercent);
                    LocalBroadcastManager.getInstance(UploadGalleryService.this).sendBroadcast(intent);
                }
            };
            if (mTimer != null && mTimerTask != null) {
                mTimer.schedule(mTimerTask, 300, 1000);//执行定时器中的任务
            }
        }
    }

    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "news_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Stop_File_Upload")) {
                //中止上传任务
                stopUpload=true;
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
        stopTimer();
    }

    /**
     * 停止定时器，初始化定时器开关
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
}